﻿using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using System;
using UnityEngine;
using xiaoye97;

namespace GeneralTech
{
    [BepInPlugin("com.xwltz.plugin.Dyson.GeneralTech", "通用科技", "2.0.0")]
    [BepInProcess("DSPGAME.exe")]
    public class GeneralTech : BaseUnityPlugin
    {
		private static ConfigEntry<int> 增加地基的数量;
		private static ConfigEntry<KeyCode> 增加地基的热键;

		private static ConfigEntry<int> 增加沙土的数量;
		private static ConfigEntry<KeyCode> 增加沙土的热键;

		private static ConfigEntry<float> 太阳帆寿命;
		private static ConfigEntry<float> 机甲步行速度;

		private static ConfigEntry<float> 物流运输机飞行速度;
		private static ConfigEntry<int> 物流运输机运载量;

		private static ConfigEntry<float> 星际物流运输船航行速度;
		private static ConfigEntry<float> 星际物流运输船曲速速度;
		private static ConfigEntry<int> 星际物流运输船运载量;

		private static ConfigEntry<int> 传送带速度;
		private static ConfigEntry<int> 分拣器速度;

		private static ConfigEntry<float> 矩阵合成速度;
		private static ConfigEntry<float> 矩阵研究速度;

		private static ConfigEntry<int> 设备生产速度;

		private static ConfigEntry<float> 资源消耗倍率;
		public static ConfigEntry<int> 物品堆叠倍率;

		private static ConfigEntry<int> 风力能发电率;
		private static ConfigEntry<int> 太阳能发电率;
		private static ConfigEntry<int> 储电池储电率;

		private static ConfigEntry<int> 资源输入倍率;
		private static ConfigEntry<int> 资源输出倍率;

		private static string 星球信息;
		private static readonly Rect Rect = new Rect(30f, 30f, 100f, 200f);
		private static readonly GUIStyle Style = new GUIStyle();

		private void Start()
		{
			Style.fontSize = 18;
			Style.normal.textColor = new Color(255f, 255f, 255f);

			#region 获得基地

			Config.Bind("AddFoundation", "readme", true, "I键增加地基数量");
			增加地基的数量 = Config.Bind("AddFoundation", "每次增加地基的数量", 5000, "每次增加地基的数量");
			增加地基的热键 = Config.Bind("AddFoundation", "增加地基的热键", KeyCode.I, "增加地基的热键");

			#endregion

			#region 获得沙土

			Config.Bind("AddSand", "readme", true, "O键增加地基数量");
			增加沙土的数量 = Config.Bind("AddSand", "每次增加沙土的数量", 50000, "每次增加沙土的数量");
			增加沙土的热键 = Config.Bind("AddSand", "增加沙土的热键", KeyCode.O, "增加沙土的热键");

			#endregion

			#region 通用设置

			Config.Bind("GeneralTech", "readme", true, "每次设置好之后一定要存档，在读取存档才会生效！！！！");
			太阳帆寿命 = Config.Bind("GeneralTech", "太阳帆寿命", 9600f, "太阳帆的使用寿命（初始值:400f, 满级3600f）");
			机甲步行速度 = Config.Bind("GeneralTech", "机甲行走速度", 20f, "机甲行走速度（初始值:5f）");

			物流运输机飞行速度 = Config.Bind("GeneralTech", "物流运输机飞行速度", 18f, "物流运输机飞行速度（初始值:8f）");
			物流运输机运载量 = Config.Bind("GeneralTech", "物流运输机运载量", 100, "物流运输机运载量（初始值:25）");

			星际物流运输船航行速度 = Config.Bind("GeneralTech", "星际物流运输船航行速度", 1500f, "星际物流运输船航行速度（初始值:400f）");
			星际物流运输船曲速速度 = Config.Bind("GeneralTech", "星际物流运输船曲速速度", 1200000f, "星际物流运输船曲速速度（初始值:400000f）");
			星际物流运输船运载量 = Config.Bind("GeneralTech", "星际物流运输船运载量", 2500, "星际物流运输船运载量（初始值:200）");

			传送带速度 = Config.Bind("GeneralTech", "传送带速度", 10, "传送带速度（建议不要超过10）");
			分拣器速度 = Config.Bind("GeneralTech", "分拣器速度", 6, "分拣器速度（建议不要超过10）");
			矩阵合成速度 = Config.Bind("GeneralTech", "矩阵合成速度", 2f, "矩阵合成速度");
			矩阵研究速度 = Config.Bind("GeneralTech", "矩阵研究速度", 2f, "矩阵研究速度");

			设备生产速度 = Config.Bind("GeneralTech", "设备生产速度", 4, "设备生产速度");

			资源消耗倍率 = Config.Bind("GeneralTech", "资源消耗倍率", 0.7f, "资源消耗倍率 0为不消耗");
			物品堆叠倍率 = Config.Bind("GeneralTech", "物品堆叠倍率", 50, "物品堆叠倍率");

			#endregion

			#region 电力设备

			风力能发电率 = Config.Bind("SuperPower", "风力能发电倍率", 8, "风力能发电倍率");
			太阳能发电率 = Config.Bind("SuperPower", "太阳能发电倍率", 8, "太阳能发电倍率");
			储电池储电率 = Config.Bind("SuperPower", "储电池储电倍率", 10, "储电池储电倍率");

			#endregion

			#region 装配工艺

			资源输入倍率 = Config.Bind("FastAssembly", "资源输入倍率", 1, "资源输入倍率");
			资源输出倍率 = Config.Bind("FastAssembly", "资源输出倍率", 3, "资源输出倍率");

            #endregion

            #region 修改游戏内相关数据

            LDBTool.EditDataAction = (Action<Proto>)Delegate.Combine(LDBTool.EditDataAction, new Action<Proto>(MyEdit));

            #endregion

            Harmony.CreateAndPatchAll(typeof(GeneralTech));
		}

		private void Update()
		{
			var isAddFoundation = GameMain.mainPlayer != null && Input.GetKeyDown(增加地基的热键.Value);
			if (isAddFoundation) GameMain.mainPlayer.package.AddItem(1131, 增加地基的数量.Value);

			var isAddSand = GameMain.mainPlayer != null && Input.GetKeyDown(增加沙土的热键.Value);
			if (isAddSand) GameMain.mainPlayer.SetSandCount(GameMain.mainPlayer.sandCount + 增加沙土的数量.Value);
		}

		private void OnGUI()
		{
			var isPlants = 星球信息 != null;
			if (isPlants) GUI.Label(Rect, 星球信息, Style);
		}

		private void MyEdit(Proto proto)
        {
			bool isItem = proto is ItemProto || proto is RecipeProto || proto is TechProto;
			if (isItem)
            {

            }

		} 

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameHistoryData), "Import")]
		private static void Postfix(GameHistoryData __instance)
		{
			__instance.solarSailLife = 太阳帆寿命.Value;
			__instance.logisticDroneSpeed = 物流运输机飞行速度.Value;
			__instance.logisticDroneCarries = 物流运输机运载量.Value;
			__instance.logisticShipSailSpeed = 星际物流运输船航行速度.Value;
			__instance.logisticShipWarpSpeed = 星际物流运输船曲速速度.Value;
			__instance.logisticShipCarries = 星际物流运输船运载量.Value;

			__instance.miningCostRate = 资源消耗倍率.Value;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Mecha), "Import")]
		private static void Postfix(Mecha __instance)
		{
			__instance.walkSpeed = 机甲步行速度.Value;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PrefabDesc), "ReadPrefab")]
		private static void Postfix(PrefabDesc __instance)
		{
			__instance.beltSpeed = 传送带速度.Value;
			__instance.inserterSTT = 分拣器速度.Value;
			__instance.labAssembleSpeed = 矩阵合成速度.Value;
			__instance.labResearchSpeed = 矩阵研究速度.Value;

			__instance.assemblerSpeed = 10000 * 设备生产速度.Value;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(StorageComponent), "LoadStatic")]
		private static void Postfix()
		{
			if (StorageComponent.staticLoaded) return;
			StorageComponent.itemIsFuel = new bool[12000];
			StorageComponent.itemStackCount = new int[12000];
			for (var i = 0; i < 12000; i++) StorageComponent.itemStackCount[i] = 1000;
			var dataArray = LDB.items.dataArray;
			foreach (var t in dataArray)
			{
				StorageComponent.itemIsFuel[t.ID] = t.HeatValue > 0L;
				StorageComponent.itemStackCount[t.ID] = t.StackSize * 物品堆叠倍率.Value;
			}

			StorageComponent.staticLoaded = true;
		}

        #region version 0.6.16.5780 已失效

        [HarmonyPostfix]
        [HarmonyPatch(typeof(PowerSystem), "NewGeneratorComponent")]
        private static void Postfix(PowerSystem __instance, int __result)
        {
            PowerGeneratorComponent[] genPool = __instance.genPool;

            #region ===========================太阳能===========================

            bool photovoltaic = genPool[__result].photovoltaic;
            if (photovoltaic)
            {
                PowerGeneratorComponent[] array = genPool;
                array[__result].genEnergyPerTick = array[__result].genEnergyPerTick * 太阳能发电率.Value;
            }

            #endregion

            #region ===========================风力能===========================

            bool wind = genPool[__result].wind;
            if (wind)
            {
                PowerGeneratorComponent[] array = genPool;
                array[__result].genEnergyPerTick = array[__result].genEnergyPerTick * 风力能发电率.Value;
            }

            #endregion

            #region ===========================储电池===========================

            //PowerAccumulatorComponent[] accPool = __instance.accPool;

            //// 输入
            //PowerAccumulatorComponent[] arrayInput = accPool;
            //arrayInput[__result].inputEnergyPerTick = arrayInput[__result].inputEnergyPerTick * 储电池储电率.Value;

            //// 输出
            //PowerAccumulatorComponent[] arrayOut = accPool;
            //arrayOut[__result].outputEnergyPerTick = arrayOut[__result].outputEnergyPerTick * 储电池储电率.Value;

            //// 容量
            //PowerAccumulatorComponent[] arrayEnergy = accPool;
            //arrayEnergy[__result].maxEnergy = arrayEnergy[__result].maxEnergy * 储电池储电率.Value;

            #endregion
        }

        #endregion

        [HarmonyPostfix]
		[HarmonyPatch(typeof(AssemblerComponent), "SetRecipe")]
		private static void Postfix(AssemblerComponent __instance)
		{
			bool flag = __instance.recipeId != 0;
			if (flag)
			{
				for (int i = 0; i < __instance.requireCounts.Length; i++)
				{
					__instance.requireCounts[i] *= 资源输入倍率.Value;
				}
				for (int j = 0; j < __instance.productCounts.Length; j++)
				{
					__instance.productCounts[j] *= 资源输出倍率.Value;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIVirtualStarmap), "OnGalaxyDataReset")]
		private static void Postfix(UIVirtualStarmap __instance)
		{
			var galaxyData = __instance.galaxyData;
			var flag = galaxyData == null;
			if (flag)
			{
				星球信息 = null;
			}
			else
			{
				var birthStarId = galaxyData.birthStarId;
				var starData = galaxyData.StarById(birthStarId);
				var planets = starData.planets;
				星球信息 = "Start Info:";
				foreach (var t in planets)
				{
					var singularityString = t.singularityString;
					if (!string.IsNullOrEmpty(singularityString))
						singularityString = " - " + t.singularityString.Trim();
					var typeString = t.typeString;
					if ("地中海".Equals(typeString)) typeString = "【Birth Point】" + typeString;
					星球信息 = 星球信息 + "\n" + t.name + "：" + typeString + singularityString;
				}
			}
		}
	}
}
